<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

import { ElMessage } from 'element-plus'
import { User, Lock, View, Hide } from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(false)
const showPassword = ref(false)

const loginForm = reactive({
  loginId: '',
  password: ''
})

const rules = {
  loginId: [
    { required: true, message: '로그인 ID를 입력하세요', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '비밀번호를 입력하세요', trigger: 'blur' },
    { min: 6, message: '비밀번호는 최소 6자 이상이어야 합니다', trigger: 'blur' }
  ]
}

const formRef = ref()

async function handleLogin() {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || ''
    const response = await fetch(`${API_BASE_URL}/api/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      credentials: 'include',
      body: JSON.stringify({
        identifier: loginForm.loginId.trim(),
        password: loginForm.password,
        rememberMe: false,
      }),
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.error || '로그인 실패')
    }



    // 获取用户详细信息以确定角色
    const meResponse = await fetch(`${API_BASE_URL}/api/auth/me`, {
      credentials: 'include',
    })

    if (!meResponse.ok) {
      throw new Error('사용자 정보 가져오기 실패')
    }

    const userInfo = await meResponse.json()

    // 检查用户角色权限
    if (userInfo.role !== 'admin' && userInfo.role !== 'partner') {
      throw new Error('관리자 페이지 접근 권한이 없습니다')
    }

    // 保存用户信息到store
    authStore.setToken('logged-in') // 简单标记已登录
    authStore.user = {
      id: userInfo.id,
      name: userInfo.name || userInfo.nickname || userInfo.loginId,
      role: userInfo.role,
      loginId: userInfo.loginId,
      email: userInfo.email,
    }

    ElMessage.success('로그인 성공!')
    router.push('/dashboard')
    
  } catch (error: any) {
    ElMessage.error(error.message || '로그인 중 오류가 발생했습니다')
  } finally {
    loading.value = false
  }
}

function togglePasswordVisibility() {
  showPassword.value = !showPassword.value
}
</script>

<template>
  <div class="login-container">
    <div class="login-card">
      <!-- Logo和标题 -->
      <div class="login-header">
        <div class="logo">
          <el-icon size="48" color="#409EFF">
            <User />
          </el-icon>
        </div>
        <h1 class="title">관리자 모바일</h1>
        <p class="subtitle">관리자 계정으로 로그인하세요</p>
      </div>

      <!-- 登录表单 -->
      <el-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        class="login-form"
        size="large"
      >
        <el-form-item prop="loginId">
          <el-input
            v-model="loginForm.loginId"
            placeholder="로그인 ID"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="비밀번호"
            :prefix-icon="Lock"
            clearable
            @keyup.enter="handleLogin"
          >
            <template #suffix>
              <el-icon 
                class="password-toggle" 
                @click="togglePasswordVisibility"
              >
                <View v-if="!showPassword" />
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleLogin"
            class="login-button"
          >
            {{ loading ? '로그인 중...' : '로그인' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  min-height: calc(var(--vh, 1vh) * 100);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-card {
  width: 100%;
  max-width: 400px;
  background: var(--el-bg-color);
  border-radius: 16px;
  padding: 32px 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  margin-bottom: 16px;
}

.title {
  font-size: 24px;
  font-weight: 700;
  color: var(--el-text-color-primary);
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 0;
}

.login-form {
  width: 100%;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.login-form :deep(.el-input__inner) {
  height: 48px;
  border-radius: 12px;
}

.login-button {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
}

.password-toggle {
  cursor: pointer;
  color: var(--el-text-color-placeholder);
  transition: color 0.2s ease;
}

.password-toggle:hover {
  color: var(--el-text-color-regular);
}
</style>
